<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\exception\UploadException;
use app\common\library\Upload;
use app\common\model\Area;
use app\common\model\Attachment;
use app\common\model\Version;
use OSS\OssClient;
use think\captcha\Captcha;
use think\Config;
use think\Hook;
use think\Loader;
use think\Log;
use think\Response;
use Throwable;

class Common extends Api
{
    protected $noNeedLogin = ['init', 'upload', 'captcha', 'info'];
    protected $noNeedRight = '*';

    public function _initialize()
    {
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header('Access-Control-Expose-Headers: __token__');//跨域让客户端获取到
        }
        check_cors_request();
        if (!isset($_COOKIE['PHPSESSID'])) {
            Config::set('session.id', $this->request->server("HTTP_SID"));
        }
        parent::_initialize();
    }

    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng    = $this->request->request('lng');
            $lat    = $this->request->request('lat');
            $upload = Config::get('upload');
            //如果非服务端中转模式需要修改为中转
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                //临时修改上传模式为服务端中转
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);
                $upload = \app\common\model\Config::upload();
                // 上传信息配置后
                Hook::listen("upload_config_init", $upload);
                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }
            $upload['cdnurl']    = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);
            $content             = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    /**
     * @throws Throwable
     */
    public function upload()
    {
        if (get_addon_config('alioss')) {
            $this->oss();
        } else {
            Config::set('default_return_type', 'json');
            Config::set('upload.cdnurl', '');
            $chunkId = $this->request->post("chunkid");
            if ($chunkId) {
                if (!Config::get('upload.chunking')) {
                    $this->error(__('Chunk file disabled'));
                }
                $action     = $this->request->post("action");
                $chunkindex = $this->request->post("chunkindex/d");
                $chunkcount = $this->request->post("chunkcount/d");
                $filename   = $this->request->post("filename");
                $method     = $this->request->method(true);
                if ($action == 'merge') {
                    $attachment = null;
                    //合并分片文件
                    try {
                        $upload     = new Upload();
                        $attachment = $upload->merge($chunkId, $chunkcount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                    $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
                } elseif ($method == 'clean') {
                    //删除冗余的分片文件
                    try {
                        $upload = new Upload();
                        $upload->clean($chunkId);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                    $this->success();
                } else {
                    //上传分片文件
                    //默认普通上传文件
                    $file = $this->request->file('file');
                    try {
                        $upload = new Upload($file);
                        $upload->chunk($chunkId, $chunkindex, $chunkcount);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                    $this->success();
                }
            } else {
                $attachment = null;
                $file       = $this->request->file('file');

                try {
                    $upload     = new Upload($file);
                    $attachment = $upload->upload();
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success('', [
                    'url'     => $attachment->url,
                    'fullurl' => cdnurl($attachment->url, true),
                ]);
            }
        }
    }

    /**
     * @throws Throwable
     */
    private function oss()
    {
        $config          = get_addon_config('alioss');
        $accessKeyId     = $config['accessKeyId'];
        $accessKeySecret = $config['accessKeySecret'];
        $endpoint        = $config['endpoint'];
        Loader::addNamespace('OSS', ADDON_PATH . 'alioss' . DS . 'library' . DS . 'OSS' . DS);
        $oss             = new OssClient($accessKeyId, $accessKeySecret, $endpoint);
        $checkDeleteFile = function ($attachment, $upload, $force = false) use ($config) {
            if ((isset($config['serverbackup']) && !$config['serverbackup']) || $force) {
                if ($attachment && !empty($attachment['id'])) {
                    $attachment->delete();
                }
                if ($upload) {
                    $filePath = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
                    @unlink($filePath);
                }
            }
        };
        $chunkId         = $this->request->post("chunkid");
        if ($chunkId) {
            $action     = $this->request->post("action");
            $chunkIndex = $this->request->post("chunkindex/d");
            $chunkCount = $this->request->post("chunkcount/d");
            $filename   = $this->request->post("filename");
            $key        = $this->request->post("key");
            $uploadId   = $this->request->post("uploadId");
            if ($action == 'merge') {
                $attachment = null;
                $upload     = null;
                if ($config['uploadmode'] == 'server') {
                    try {
                        $upload     = new Upload();
                        $attachment = $upload->merge($chunkId, $chunkCount, $filename);
                    } catch (UploadException $e) {
                        $this->error($e->getMessage());
                    }
                }
                $tags = $this->request->post("etags/a", []);
                if (count($tags) != $chunkCount) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("分片数据错误");
                }
                $listParts = [];
                for ($i = 0; $i < $chunkCount; $i++) {
                    $listParts[] = ["PartNumber" => $i + 1, "ETag" => $tags[$i]];
                }
                try {
                    $eTag = $oss->completeMultipartUpload($config['bucket'], $key, $uploadId, $listParts);
                } catch (\Exception $e) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error($e->getMessage());
                }
                $result = json_decode(json_encode(simplexml_load_string($eTag['body'], "SimpleXMLElement", LIBXML_NOCDATA)), true);
                if (!isset($result['Key'])) {
                    $checkDeleteFile($attachment, $upload, true);
                    $this->error("上传失败(1001)");
                } else {
                    $checkDeleteFile($attachment, $upload);
                    $this->success("上传成功", '', [
                        'url'     => "/" . $key,
                        'fullurl' => cdnurl("/" . $key, true),
                    ]);
                }
            } else {
                $file   = $this->request->file('file');
                $upload = new Upload($file);
                $file   = $upload->chunk($chunkId, $chunkIndex, $chunkCount);
                $eTag   = $oss->uploadPart($config['bucket'], $key, $uploadId, ['fileUpload' => $file->getRealPath(), 'partNumber' => $chunkIndex + 1]);
                $this->success('', [], 1, null, ['ETag' => $eTag]);
            }
        } else {
            $upload     = new Upload($this->request->file('file'));
            $attachment = $upload->upload();
            $filePath   = $upload->getFile()->getRealPath() ?: $upload->getFile()->getPathname();
            $url        = $attachment->url;
            try {
                $oss->uploadFile($config['bucket'], ltrim($url, "/"), $filePath);
            } catch (Throwable $e) {
                $checkDeleteFile($attachment, $upload, true);
                Log::write($e->getMessage());
                $this->error("上传失败(1002)");
            }
            $checkDeleteFile($attachment, $upload);

            $data = $attachment->toArray();
            unset($data['id']);
            $data['storage'] = 'alioss';
            Attachment::create($data, true);

            $this->success('', [
                'url'     => $url,
                'fullurl' => cdnurl($url, true),
            ]);
        }
    }

    public function captcha($id = ""): Response
    {
        Config::set([
            'captcha' => array_merge(config('captcha'), [
                'fontSize' => 44,
                'imageH'   => 150,
                'imageW'   => 350,
            ]),
        ]);
        $captcha = new Captcha((array)Config::get('captcha'));
        return $captcha->entry($id);
    }

    public function info()
    {
        $this->success('', config('site'));
    }
}
